package com.gvfish.service;

import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gvfish.core.CacheSingleton;
import com.gvfish.dao.LinkDao;
import com.gvfish.entity.Link;

@Service
@Transactional
public class LinkManager {
	private static String LINK_STRING="linkStr";
	@Autowired
	private LinkDao linkDao;
	static {
		try {
			CacheSingleton.getInstance().init(Collections.emptyMap());
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	private static Cache cache = CacheSingleton.getInstance().getCache();
	
	public List<Link> findAll() {
//		return linkDao.getAll();
		return linkDao.findAll();
	}
	public Link find(Long linkId){
		return linkDao.getById(linkId);
	}
	public void del(Long id){
		linkDao.del(id);
	}
	public Link save(Link link){
		removeLinkCache();
		 linkDao.save(link);
		 return link;
	}
	@SuppressWarnings("unchecked")
	public String getLinkStr(){
		System.out.println("in get linkstr");
		String linkStr = (String)cache.get(LINK_STRING);
		List<Link> links = linkDao.findAll();
//		List<Link> links = linkDao.getAll();
		if(linkStr==null&&links!=null){
			StringBuilder sb = new StringBuilder();
			for(Link link:links){
				sb.append("<a href='");
				sb.append(link.getUrl());
				sb.append("' target='blank'>");
				sb.append(link.getSiteName());
				sb.append("</a>");
				sb.append("<br>");
			}
			linkStr=sb.toString();
			cache.put(LINK_STRING, linkStr);
		}
		return linkStr;
	}
	
	/**
	 * 新增或修改实体后移除缓存
	 */
	public void removeLinkCache(){
		cache.remove(LINK_STRING);
	}
	public void update(Link link){
		Assert.notNull(link);
		linkDao.update(link, link.getId());
	}
}
